package com.sboot.springboot_demo.service;

import com.sboot.springboot_demo.util.Tool;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.util.zip.ZipOutputStream;

/**
 * @author luheng
 * @create 2019/8/14
 */
@Service
public class ZipService {

    @Value("${create.zip.sourcefilepath}")
    private String sourceFilePath;

    @Value("${create.zip.zipfilepath}")
    private String zipFilePath;

    @Value("${create.zip.filename}")
    private String fileName;

    @Value("${create.zip.suffix}")
    private String suffix;

    public void create(HttpServletResponse response) {
        try {
            createZip(zipFilePath + File.separator + fileName + suffix,response);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    public void createFile(String string,String path,String name) throws IOException {
        File file=new File(sourceFilePath);
        if(!file.exists()){//如果文件夹不存在
            file.mkdirs();//创建文件夹
        }
        FileWriter fileWriter= null;
        fileWriter = new FileWriter(path + File.separator + name);
        fileWriter.write(string);
        fileWriter.flush();
        fileWriter.close();
    }

    /**
     * sourceFilePath：需要被压缩的文件路径
     * @param path:生成存放压缩包的文件路径+压缩包名称.后缀
     * @param response
     * @throws Exception
     */
    public void createZip(String path, HttpServletResponse response) throws Exception {
        File fileZip = new File(path);
        FileOutputStream outStream = new FileOutputStream(fileZip);
        ZipOutputStream toClient = new ZipOutputStream(outStream);
        Tool.compress(new File(sourceFilePath), toClient, "", true);
        toClient.close();
        outStream.close();
        // 下载,并删除临时文件zip
        Tool.downloadFile("",fileZip, response, true);
    }
}
